/**
 * 获取地址信息
 */
var d1 = require("deviceone");
var dojs = require("dojs");
var do_Network = d1.sm("do_Network");
var dataCache = d1.sm("do_DataCache");
var do_Page = d1.sm("do_Page");
var do_Global = d1.sm("do_Global");

//各级地址,存放数组
var provinceArray = [];
var cityObject = {};
var districtObject = {};
var isp = false;
var isc = false;
//获取地址
module.exports.obtainAddressInfo = function(){
	
	//判断是否有网络
	if (dojs.core.valueEqual(do_Network.getStatus(), "none")) {
		//本地获取
		var data = dataCache.loadData(do_Global.getMemory("data_label").address);
		dealSuccess(data);
		
	}else{
		dojs.http.ajax({
			url : do_Global.getMemory("address_url"),
			type : "GET",
			success : function(data) {//返回值data本身就是json对象
			
				if (! data.success) {
					dojs.core.p(data.message);
					return;
				}
				//存储地址
				dataCache.saveData(do_Global.getMemory("data_label").address, data.data)
				dealSuccess(data.data);
				
			},
			error : function(data) {
				dojs.core.p("网络错误");
			}
		});
	}
};
//处理返回的地址
function dealSuccess(data) {
	var L = data.length;
	try {
		for (var i = 0 ; i < L; i++) {
			var p = data[i];
			provinceArray.push({name:p.province,id:p.regionId,code:p.code});
			if (p.childrens.length >= 0) {
				//解析市级地址
				try {
					parseCity(p.province,p.childrens);
					isc = true;
				} catch (e) {
					isc = false;
				}
			}
		}
		isp = true;
	} catch (e) {
		// TODO: handle exception
		isp = false;
	}
	//全部解析完毕
	do_Page.fire("addressParseCompleted", {
		iscomplete:isp && isc,
		province:provinceArray,
		city:cityObject,
		district:districtObject});
}
//解析市级地址
function parseCity(key,childrens) {
	var L = childrens.length;
	var cityArray = [];
	for (var i = 0; i < L; i++) {
		var c = childrens[i];
		cityArray.push({name:c.city,id:c.regionId,code:c.code});
		if (c.childrens.length > 0) {
			parseDistrict(c.city, c.childrens);
		}
	}
	cityObject[key] = cityArray;
}
//解析县级地址
function parseDistrict(key,childrens) {
	var L = childrens.length;
	var districtArray = [];
	for (var i = 0; i < L; i++) {
		var c = childrens[i];
		districtArray.push(c.city);
	}
	districtObject[key] = districtArray;
}


